from flask_restful import Resource
from werkzeug.security import check_password_hash, generate_password_hash

from model.crud import UpdateInstance, QueryOneInstance
from model.tables import User
from restful.data import DataUsernamePassword
from restful.error import RenderUserNotAdmin
from restful.response import ResponseSuccess, ResponseNotFound, ResponseUnauthorized, ResponseConflict
from restful.session import login_required, add_session, del_session, data


class SerRegister(Resource):
    @data(DataUsernamePassword())
    def post(self, data):
        existing_user = QueryOneInstance(User, {'username': data['username']})
        if existing_user:
            return ResponseConflict("用户已存在")

        user = User(username=data['username'], password=generate_password_hash(data['password']))
        UpdateInstance(user)
        return ResponseSuccess(msg="注册用户成功")

class SerLogin(Resource):
    @data(DataUsernamePassword())
    def post(self, data):
        user = QueryOneInstance(User, {'username': data['username']})
        if not user:
            return ResponseNotFound("用户不存在")

        if not check_password_hash(user.password, data['password']):
            return ResponseUnauthorized("用户密码错误")

        add_session(user.id)
        return ResponseSuccess(msg="登录成功")

    @login_required
    def delete(self):
        del_session()
        return ResponseSuccess("登出成功")

class AdminLogin(Resource):
    @data(DataUsernamePassword())
    def post(self, data):
        user = QueryOneInstance(User, {'username': data['username']})
        if not user:
            return ResponseNotFound("用户不存在")

        if not check_password_hash(user.password, data['password']):
            return ResponseUnauthorized("用户密码错误")

        if not user.admin:
            return RenderUserNotAdmin(user.id)

        add_session(user.id)
        return ResponseSuccess(msg="登录成功")

    @login_required
    def delete(self):
        del_session()
        return ResponseSuccess("登出成功")

